<template>
	<view class="body-view">
		<!--导航和状态栏-->
		<view class="state-navigation">
			<view class="slim_header_navigation d-flex a-center j-center" >
				<view class="left_box" @tap="goBack">
					<image src="/static/center/back.png" class="back"></image>
				</view>
				<view class="title">设置</view>
				<view class="right_box">
					<!-- <image src="/static/center/dian.png" class="dian"></image> -->
				</view>
			</view>
		</view>
		<!-- 顶部位置占位 -->
		<view style="height:calc(100rpx + var(--status-bar-height));"></view>
		<view class="setUp-all">
			<view class="content-all">
				<view class="content-row d-flex a-center" @tap="goAccountSetting">
					<view class="row-text">账号与安全</view>
					<i class="icon row-icon icon-more-2"></i>
				</view>
				<view class="content-row d-flex a-center" @tap="goPrivacySetting">
					<view class="row-text">隐私设置</view>
					<i class="icon row-icon icon-more-2"></i>
				</view>
				<view class="content-row noactive d-flex a-center j-between">
					<view class="row-text">新消息通知</view>
					<tm-switch
                        linear="left"
                        linearDeep="accent"
                        v-model="needNotice"
                        :defaultValue="needNotice"
                        @change="handleChange"
                        color="rgba(15, 95, 70, 0.30)"
                        :barColor="
                            needNotice
                                ? 'rgba(35, 226, 166, 1)'
                                : 'rgba(195, 204, 202, 1)'
                        "
                        barIcon=""
                        size="normal"
                    ></tm-switch>
				</view>
				<view class="content-row d-flex a-center" @tap="goStatement">
					<view class="row-text">声明与文献</view>
					<i class="icon row-icon icon-more-2"></i>
				</view>
				<!-- <view class="content-row d-flex a-center">
					<view class="row-text">帮助与反馈</view>
					<i class="icon row-icon icon-more-2"></i>
				</view> -->
				<view class="content-row d-flex a-center" @tap="goUserAgreement">
					<view class="row-text">用户协议</view>
					<i class="icon row-icon icon-more-2"></i>
				</view>
				<view class="content-row d-flex a-center" @tap="goPrivacyPolicy">
					<view class="row-text">隐私政策</view>
					<i class="icon row-icon icon-more-2"></i>
				</view>
				<view class="content-row d-flex a-center" @tap="openPopup('clearStorge')">
					<view class="row-text">清除缓存</view>
					<i class="icon row-icon icon-more-2"></i>
				</view>
				<view class="content-row d-flex a-center" @tap="openPopup('clearAllMessage')">
					<view class="row-text">清空聊天记录</view>
					<i class="icon row-icon icon-more-2"></i>
				</view>
				<view class="content-row d-flex a-center" @tap="goAbout">
					<view class="row-text">关于</view>
					<i class="icon row-icon icon-more-2"></i>
				</view>
			</view>
		</view>


        <view class="btn_bottom_box">
            <view class="btn_main_r" @tap="openPopup('loginOut')">
                <text class="text" style="font-weight:600;">退出登录</text>
            </view>
                <view class="bottom_seat"></view>
        </view>

		<!--
		<view class="bottom-button w-center d-flex a-center j-center">退出登录</view>
		-->


        <uni-popup
            ref="popup"
            background-color="transparent"
            :safe-area="false"
        >   


            <view class="sys-confirm-content">
				<view class="confirm-content-title">{{currentPop.desp}}</view>
				<!-- <view class="confirm-content-tip">
					<view class="content-tip-row" style="color: #cc3300;">同时删除与该联系人的聊天记录</view>
				</view> -->
				<view  @tap="popConfirm" class="content-button button-confirm" style="color: #1DC691;">确认</view>
				<view style="height: 20rpx; background: #f5f5f5"></view>
				<view @tap="closePopup" class="content-button" style="color: #999999;">取消</view>
		    </view>
            <!-- <view class="popup-content">


                
                <view class="desp d-flex a-center">{{currentPop.desp}}</view>
                <view class="row d-flex a-center j-center error" @tap="popConfirm">{{currentPop.confirm}}</view>
                <view style="height: 20rpx; background: #f5f5f5"></view>
                <view
                    class="row d-flex a-center j-center cancel"
                    @tap="closePopup"
                    >取消</view
                >
            </view> -->
        </uni-popup>
		
	</view>
</template>

<script setup lang="tsx" name="setUp">
import { ref } from "vue";
import {
    onReady,
    onShow,
    onHide,
    onBackPress,
    onLoad,
    onUnload,
    onPageScroll,
} from "@dcloudio/uni-app";
import { loginOut as imLoginOut } from '@/hooks/imLogin'
import { clearHistoryMessage } from '@/hooks/imHooks'
import {
    loginOut,getUserDetail,
} from "@/api/api";
import { userData as userDataStore } from "@/store/userData";
import { config as configStore }  from '@/store/config'
import { imStore }  from '@/store/imStore'
import {showLoading,closeLoading,wait} from '@/utils/utils'
import { activeBar } from "@/store/activeBar";

const ACTIVE_BAR = activeBar();


const goBack = () => {
	uni.navigateBack();
};
//跳转账号与安全页面
const goAccountSetting = () => {
	uni.navigateTo({
		url:`/pages/accountSetting/accountSetting`
	});
};
//跳转隐私设置页面
const goPrivacySetting = () => {
	uni.navigateTo({
		url:`/pages/privacySetting/privacySetting`
	});
};
const goAbout = () => {
	uni.navigateTo({
		url:`/pages/setUp/about`
	});
};
const goStatement = () => {
	uni.navigateTo({
		url:`/pages/setUp/statement`
	});
};

const goUserAgreement = ()=>{
    uni.navigateTo({
		url:`/pages/webview/webview?title=用户协议&url=http://52pp365.com/yonghuxieyi.html`
	});
}

const goPrivacyPolicy = ()=>{
    uni.navigateTo({
		url:`/pages/webview/webview?title=隐私政策&url=http://52pp365.com/yinsizhengce.html`
	});
}

const userData = userDataStore();
const config = configStore();
const IM_STORE = imStore();

const needNotice = ref(true);

const handleChange = async (bool:boolean) =>{
    needNotice.value = bool;
}


const popupData = {
    loginOut:{
        desp:'您将退出当前账号',
        confirm:'确认退出',
        action:'loginOut'
    },
    clearStorge:{
        desp:'您将清除应用缓存',
        confirm:'确认清除',
        action:'clearStorge'
    },
    clearAllMessage:{
        desp:'您将删除所有会话的聊天记录',
        confirm:'确认删除',
        action:'clearAllMessage'
    },
}


const currentPop = ref({});

const popup = ref(null);

const openPopup = (type) => {
    currentPop.value = popupData[type]
    popup.value.open("bottom");
};

const closePopup = () => {
    popup.value.close();
};

let confirmTaped = false;

const popConfirm = async() => {


    showLoading();

    if(confirmTaped){
        return
    }

    confirmTaped = true;

    if(currentPop.value.action==='loginOut'){
        await userLoginOut();
    }
    if(currentPop.value.action==='clearAllMessage'){
        await clearAllMessage();
    }
    if(currentPop.value.action==='clearStorge'){
        closeLoading();
        await clearStorge();
    }

    closeLoading();

    closePopup();

    confirmTaped = false;
};


const clearAllMessage = async() => {


    const { conversationList } = IM_STORE;
    for(let i=0;i<conversationList.length;i++){
        const { conversationID } = conversationList[i];

        uni.$TUIKit.TUIConversationServer.deleteConversation(
                                            conversationID
                                        ).then((imResponse: any) => {
                                            //const { conversationID } = imResponse.data;
                                        });

        //await clearHistoryMessage(conversationID).catch();
    }

    uni.showToast({
            icon: "none",
            title: '已清除全部聊天记录',
            duration: 2000,
    });

    closePopup();
}

const clearStorge = async() => {
    const _token = uni.getStorageSync('api_token');
    const _s_userData = uni.getStorageSync('userData');
    const _first_open = uni.getStorageSync('first_open');
    const _unfinishAppleOrder1 = uni.getStorageSync('unfinishAppleOrder1');
    const _ver = uni.getStorageSync('ver');
    const _userData = {
        id: userData.id,
        token:userData.token,
        nickName:userData.nickName,
        openid:userData.openid,
        photo:userData.photo,
        sex:userData.sex,
        phone:userData.phone,
    }


    uni.clearStorageSync();
    uni.setStorageSync("api_token", _token);
    uni.setStorageSync("first_open", _first_open);
    uni.setStorageSync("userData", _s_userData);
    uni.setStorageSync('popup_readed',true);
    uni.setStorageSync('unfinishAppleOrder1',_unfinishAppleOrder1);
    uni.setStorageSync('ver',_ver);
    

    userData.setUserData(_userData)
    uni.showToast({
        icon: "none",
        title: '已清除缓存',
        duration: 2000,
    });


}

const GetUserData = async (userId: string) => {
    const detail: any = await getUserDetail({ id: userId });
    const { flag, data } = detail;
    if (flag !== 1) {
        uni.showToast({
            icon: "none",
            title: '获取用户信息失败，请稍后再试',
            duration: 1500,
        });
        return
    }
    const { id, nickName, openid, photo, sex, phone } = data;

    const obj = { id, nickName, openid, photo, sex, phone }
    userData.setUserData({ id, nickName, openid, photo, sex, phone });
};




const userLoginOut = async () => {

    ACTIVE_BAR.setActiveText('记录');
	//uni.clearStorage();
    await imLoginOut();
    const res: any = await loginOut().catch();
    const { flag } = res;
    if (flag === 9000 || flag === 1) {
        userData.clearUserData();
        config.setPageUnload();
        uni.removeStorageSync('api_token');
        uni.reLaunch({
            url: "/pages/login/login",
            animationType: "fade-in",
        });
        return true;
    }
    
};



</script>

<style lang="scss" scoped>
// @import './setUp.scss';
.setUp-all{
	padding: 20rpx;
}
.btn_main {
	position: fixed;
	display: block;
	height: 80rpx;
	border-radius: 40rpx;
	line-height: 80rpx;
	bottom: calc(constant(safe-area-inset-bottom));
	bottom: calc(env(safe-area-inset-bottom));
	z-index: 10;
}
.content-all{
	background: #FFFFFF;
	border-radius: 10rpx;
	.content-row{
        padding:0 30rpx;
		height: 100rpx;
        &:active{
            background:#f5f5f5;
        }
        &.noactive{
            background:#fff;
        }
		.row-text{
			font-size: 30rpx;
			font-family: PingFangSC-Regular, PingFang SC;
			font-weight: 400;
			color: #333333;
		}
		.row-icon{
			flex: 1;
			text-align: right;
			font-size: 20rpx;
			color: #707070;;
		}
	}
}

.popup-content {
        position:relative;
        z-index:1000;
        width: 750rpx;
        border-top-left-radius: 20rpx;
        border-top-right-radius: 20rpx;
        overflow: hidden;
        background: #fff;

        .desp {
            color: #999;
            font-size: 26rpx;
            min-height: 100rpx;
            padding: 20rpx;
        }

        .row {
            height: 100rpx;
        }

        .cancel {
            color: $slim-text3;
        }
}
/*
.bottom-button{
	bottom: 80rpx;
	width: calc(100vw - 60rpx);
	height: 80rpx;
	background: linear-gradient(318deg, #64F1C5 0%, #29DBA3 100%);
	border-radius: 40rpx;
	font-size: 32rpx;
	font-family: PingFangSC-Semibold, PingFang SC;
	font-weight: 600;
	color: #FFFFFF;
}
*/

// /deep/ uni-switch .uni-switch-input:after{
// 	background-color: #23E2A6;
// }

</style>
